package com.auntvt.timo.jpax.springbootstarter.primarykey.generator;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.auntvt.timo.jpax.core.utils.SpringContextUtil;
import com.auntvt.timo.jpax.springbootstarter.config.properties.JpaxPrimaryKeyProperties;
import com.auntvt.timo.jpax.springbootstarter.primarykey.JpaxStrategy;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;
import org.springframework.stereotype.Component;

import java.io.Serializable;

/**
 * 雪花算法主键生成器
 *
 * @author 小懒虫 <auntvt@163.com>
 * @date 2021/5/28
 */
@Component(JpaxStrategy.PREFIX + JpaxStrategy.SNOW_FLAKE)
public class JpaxSnowFlakeGenerator implements IdentifierGenerator {

    /**
     * 配置对象
     */
    private JpaxPrimaryKeyProperties properties;

    @Override
    public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
        if (properties == null) {
            properties = SpringContextUtil.getBean(JpaxPrimaryKeyProperties.class);
        }

        // 生成雪花算法数据
        JpaxPrimaryKeyProperties.SnowFlake snowFlake = properties.getSnowFlake();
        Snowflake snowflake = IdUtil.getSnowflake(snowFlake.getWorkerId(), snowFlake.getDatacenterId());
        return snowflake.nextId();
    }
}
